<style lang="less">
@import './style.less';
</style>

<template>
	<span class="dialog-ex">
		<el-dialog :before-close="() => onCancelDialog()" :title="title" :visible="true">
			<!-- table-ex -->
			<div :key="formItem.prop" style="width:100%;" v-for="formItem in formItems" v-if="formItem.name === 'tablex'">
				<table-ex :columns="formItem.columns" :rows="formData.rows"/>
			</div>
			<el-form :label-width="formLabelWidth" label-position="right" v-if="formItems">
				<el-form-item
					:key="formItem.prop"
					:label="formItem.validation ? formItem.label + '*': formItem.label"
					v-for="(formItem, index) in formItems"
					v-if="formActions.formItemVisible
                                    ? formActions.formItemVisible(formItem)
                                    : (formItem.visible ? formItem.visible() : true)"
				>
					<!-- input -->
					<div style="width:100%;" v-if="formItem.name === 'input'">
						<el-input
							:disabled="formItem.disabled ? formItem.disabled : false"
							:placeholder="formItem.placeholder"
							:type="formItem.type"
							style="width:100%;"
							v-if="formItem.name === 'input'"
							v-model="formData[formItem.prop]"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>
					<!-- input-number -->
					<div style="width:100%;" v-if="formItem.name === 'input-number'">
						<el-input-number
							:disabled="formItem.disabled ? formItem.disabled : false"
							:type="formItem.type"
							v-if="formItem.name === 'input-number'"
							v-model="formData[formItem.prop]"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!--select-->
					<div v-else-if="formItem.name === 'select'">
						<el-select placeholder="请选择" v-model="formData[formItem.prop]">
							<el-option
								:key="item.value"
								:label="item.label"
								:value="item.value"
								v-for="item in fromValues && fromValues[formItem.prop] ? fromValues[formItem.prop] : fromValues"
							></el-option>
						</el-select>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!--checkbox-->
					<el-checkbox v-else-if="formItem.name === 'checkbox'" v-model="formData[formItem.prop]"/>
					<!-- cascader -->
					<div v-else-if="formItem.name === 'cascader'">
						<el-cascader
							:disabled="formItem.disabled"
							:options="fromValues && fromValues[formItem.prop] ? fromValues[formItem.prop] : fromValues"
							:placeholder="formItem.placeholder"
							:props="formItem.props"
							@change="e => handleChange(e, formItem)"
							v-model="formData[formItem.prop]"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!-- checkbox-group -->
					<el-checkbox-group v-else-if="formItem.name === 'checkbox-group'" v-model="formData[formItem.prop]">
						<el-checkbox :key="option.value" :label="option.label" v-for="option in formItem.options"></el-checkbox>
					</el-checkbox-group>

					<!-- checkbox-select -->
					<span v-else-if="formItem.name === 'checkbox-select'">
						<el-checkbox
							:key="option.value"
							:label="option.value"
							@change="selectChange(option, index, formItem)"
							v-for="option in formItem.options"
							v-model="option.checked"
						>{{option.label}}</el-checkbox>
					</span>

					<!-- tree -->
					<div v-else-if="formItem.name === 'tree'">
						<el-tree
							:data="treeData"
							:default-checked-keys="formData[formItem.prop]"
							:props="formItem.props"
							@check="data => onTreeCheck(data, formItem.prop)"
							class="tree-el"
							node-key="id"
							ref="tree"
							show-checkbox
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!-- search -->
					<div v-else-if="formItem.name === 'search'">
						<el-select
							:multiple="formItem.multiple"
							:placeholder="formItem.placeholder"
							:remote-method="onRemoteMethod"
							filterable
							remote
							reserve-keyword
							v-model="formData[formItem.prop]"
						>
							<el-option
								:key="item.id"
								:label="item.name ? item.name : item.title"
								:value="item.id"
								v-for="item in searchData"
							/>
						</el-select>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!-- media-upload -->
					<div v-else-if="formItem.name === 'media-upload'">
						<media-upload
							:data="formData"
							:media-type="mediaType"
							:prop="formItem"
							:upload-success="res => onUploadSuccess(res, formItem)"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</div>

					<!-- icon-upload -->
					<icon-upload
						:data="formData"
						:delete="onIconDelete"
						:prop="formItem"
						:purpose="formItem.purpose"
						v-else-if="formItem.name === 'icon-upload'"
					/>

					<!-- uplaod -->
					<span class="upload" v-else-if="formItem.name === 'upload'">
						<span class="upload-content">
							<el-input class="upload-content-input" disabled v-model="formData[formItem.prop]"/>
							<el-upload
								:action="`${formItem.action}?${uploadParamsStr}`"
								:name="formItem.keyName"
								:on-error="uploadError"
								:on-success="res => uploadSuccess(res, index, formItem)"
								:ref="formItem.prop"
								:show-file-list="false"
								class="upload-content-button"
							>
								<el-button>{{formItem.oprionTitle}}</el-button>
							</el-upload>
							<el-button
								@click="deleteFile(formItem.prop, index, formItem)"
								class="upload-content-cancel"
								v-if="formItem.cancelTitle"
							>{{formItem.cancelTitle}}</el-button>
						</span>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</span>

					<!-- popup -->
					<span class="el-popup" v-else-if="formItem.name === 'popup'">
						<el-input
							:disabled="formItem.disabled"
							:placeholder="formItem.placeholder"
							:type="formItem.type"
							:value="popupValue"
							@change="e => popup(formItem, e)"
							@focus="inputFocus"
							class="el-popup-input"
							style="width:100%;"
						>
							<i class="el-icon-arrow-down" slot="suffix"></i>
						</el-input>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</span>

					<!-- 时间选择器  -->
					<span v-else-if="formItem.name === 'startime'">
						<el-date-picker
							format="yyyy-MM-dd"
							placeholder="选择日期"
							style="width: 100%;"
							type="date"
							v-model="formData.startTime"
							value-format="yyyy-MM-dd"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</span>
					<span v-else-if="formItem.name === 'endtime'">
						<el-date-picker
							placeholder="选择日期"
							style="width: 100%;"
							type="date"
							v-model="formData.endTime"
							value-format="yyyy-MM-dd"
						/>
						<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
					</span>
					<span v-else-if="formItem.name === 'dateTime'">
						<el-date-picker
							placeholder="选择日期"
							style="width: 100%;"
							type="datetime"
							v-model="formData[formItem.prop]"
							value-format="yyyy-MM-dd HH:mm"
						/>
					</span>
					<!-- 单选按钮radio -->
					<el-radio-group v-else-if="formItem.name === 'radio-select'" v-model="form.resource">
						<el-radio :key="item.label" :label="item.label" v-for="item in formItem.r"/>
					</el-radio-group>

					<!-- textararea -->
					<div v-else-if="formItem.name=='textarea'">
						<el-form-item :label="formData.label">
							<el-input type="textarea" v-model="formData.textarea"></el-input>
							<div class="error-class" v-if="errors[formItem.prop]">{{formItem.label}}为必填项</div>
						</el-form-item>
					</div>

					<div class="time-input-ex" v-else-if="formItem.name === 'time-input-ex'">
						<div :key="item.minutes.prop" class="time-input-item" v-for="item in formItem.items">
							<div style="white-space:nowrap;">{{item.minutes.label}}</div>
							<el-input :type="item.minutes.type" v-model="formData[item.minutes.prop]"/>:
							<el-input :type="item.seconds.type" v-model="formData[item.seconds.prop]"/>
							{{item.seconds.label}}
						</div>
					</div>
				</el-form-item>

				<div class="dialog-footer">
					<el-button @click="onCancelDialog">取消</el-button>
					<el-button @click="onSaveAnotherDialog" v-if="another">另存为</el-button>
					<el-button @click="onConfirmDialog" type="primary">确定</el-button>
				</div>
			</el-form>
		</el-dialog>
	</span>
</template>

<script>
import { Message } from 'element-ui'
import { deepCopy, handleParams } from '@/utils/util'

import tableEx from '@/components/table/tableEx'
import mediaUpload from '@/components/custom/mediaUpload'
import iconUpload from '@/components/custom/iconUpload'
import multistage from '@/components/custom/multistage'
import { conditionalExpression } from 'babel-types'

export default {
  name: 'DialogEx',
  props: [
    'title',
    'mode',
    'labelWidth',
    'form',
    'ctrlValues',
    'init',
    'default',
    'another',

    // check group
    'groupValue',

    //search
    'searchData',
    'remoteMethod',

    // tree props
    'treeData',
    'defaultProps',

    // popup
    'popupFocus',
    'popupValue',

    // upload porps
    'uploadParams',
    'uploadFileName'
  ],

  components: {
    'table-ex': tableEx,
    'media-upload': mediaUpload,
    'icon-upload': iconUpload,
    multistage: multistage
  },

  data() {
    return {
      text: [],
      formLabelWidth: this.labelWidth ? this.labelWidth : '150px',
      formData:
        (this.mode === 'edit' ||
          this.mode == 'resetpassword' ||
          this.mode === 'weight_edit') &&
        this.init
          ? deepCopy(this.init)
          : this.form && this.form.default
          ? deepCopy(this.form.default)
          : { thumbPic: '', contentFile: '' },
      mediaType: this.form ? this.form.mediaType : null,
      formItems: this.form && this.form.items ? this.form.items : [],
      fromValues: this.ctrlValues ? this.ctrlValues : [],
      formActions: this.form && this.form.actions ? this.form.actions : {},
      checkAll: false,
      uploadParamsStr: this.uploadParams && handleParams(this.uploadParams),
      errors: {},
      popup_state: true
    }
  },
  watch: {
    popupValue(val) {
      if (val) {
        this.disableFlag('practiceType', true)
      } else {
        this.disableFlag('practiceType', false)
      }
    }
  },
  mounted() {
    console.log('mounted >> ', this.init)
    let objc = {}
    for (let item of this.formItems) {
      this.initValidations(item, objc)
    }
    this.errors = objc
  },

  methods: {
    initValidations(item, objc) {
      if (item.name === 'time-input-ex') {
        const items = item.items
        for (let timeItem of items) {
          objc[timeItem.minutes.prop] = false
          objc[timeItem.seconds.prop] = false
        }
      } else if (item.prop) {
        objc[item.prop] = false
      }
    },
    onConfirmDialog() {
      console.log(this.formData)
      console.log('popupValue: ', this.popupValue)
      let formList = this.form.items
      let judge = this.validation(this.form)
      console.log('judge', judge, this.errors)
      if (!judge) {
        return
      }
      if (this.formActions.confirm) {
        this.formActions.confirm(this.formData, this.mode)
      }
    },
    validation(data) {
      for (let item of data.items) {
        if (item.validation) {
          if (item.name === 'popup') {
            this.errors[item.prop] = !this.popupValue
          } else if (item.name === 'time-input-ex') {
            const items = item.items
            for (let timeItem of items) {
              if (
                this.formData[timeItem.minutes.prop] != null &&
                this.formData[timeItem.minutes.prop] != undefined
              ) {
                this.errors[timeItem.minutes.prop] = false
              } else {
                this.errors[timeItem.minutes.prop] = true
              }
              if (
                this.formData[timeItem.seconds.prop] != null &&
                this.formData[timeItem.seconds.prop] != undefined
              ) {
                this.errors[timeItem.seconds.prop] = false
              } else {
                this.errors[timeItem.seconds.prop] = true
              }
            }
          } else {
            if (typeof this.formData[item.prop] === 'object') {
              if (
                JSON.stringify(this.formData[item.prop]) === '{}' ||
                JSON.stringify(this.formData[item.prop]) === '[]'
              ) {
                this.errors[item.prop] = true
              } else {
                this.errors[item.prop] = false
              }
            } else {
              this.errors[item.prop] = !this.formData[item.prop]
            }
          }
        }
      }
      for (let key in this.errors) {
        if (this.errors[key]) {
          return false
        }
      }
      return true
    },
    handleChange(oper, formItem) {
        this.disableFlag(oper[0], formItem.prop)
    },
    popup(formItem, e) {
      console.log('我是测试', formItem, e)
      formItem.cb && form[formItem.cb] ? e => form[formItem.cb](formItem, e) : popup
    },
    onCancelDialog() {
      if (this.formActions.cancel) {
        this.formActions.cancel(this.form, this.mode)
      }
    },
    onSaveAnotherDialog() {
      if (this.formActions.another) {
        this.formActions.another(this.formData, this.mode)
      }
    },
    onTreeCheck(e, prop) {
      let nodes = this.$refs.tree[0].getCheckedNodes()
      let ids = nodes.map(item => {
        return item.id
      })
      this.formData[prop] = ids
    },
    onUploadSuccess(res, formItem) {
      this.formData = res
      if (this.formActions && this.formActions.uploadSuccess) {
        this.formActions.uploadSuccess(this.formData, formItem)
      }
    },
    onIconDelete(fileId, formData) {
      if (this.formActions && this.formActions.iconDelete) {
        this.formActions.iconDelete(fileId, formData)
      }
    },
    onRemoteMethod(query) {
      this.remoteMethod && this.remoteMethod(query)
    },

    /* popup */
    inputFocus(e) {
      console.log('11111')
      this.popupFocus && this.popupFocus()
    },
    /* checkbox select actions */
    selectChange(oper, index, options) {
      // -- 单选
      if (options.type === 'single') {
        for (let item of options.options) {
          if (oper.label !== item.label) {
            item.checked = false
          }
        }
        this.formItems[index] = options
        this.formData[options.prop] = oper.label
        return
      }
      // -- 多选 暂时没有看到多选参数格式
      if (options.type === 'multi') {
        let arr = []
        for (let item of options.options) {
          item.checked && arr.push(item)
        }
        this.formData[options.prop] = arr
      }
    },

    /* uplaod actions */
    uploadSuccess(res, index, options) {
      Message({
        center: true,
        type: 'success',
        message: '文件上传成功'
      })
      this.$emit('uploadSuccess', 'chengg')
      this.formData[options.prop] = res.fileUrl
      Object.assign(this.formData, {
        [`${options.keyword}`]: res.originFileName,
        [`${options.prop}`]: res.fileUrl
      })
      console.log('--uploadSuccess--')
      console.log(res)
      console.log(this.formData)
      console.log('--uploadSuccess--')
    },
    uploadError(error) {
      Message({
        center: true,
        type: 'warning',
        message: '文件上传失败'
      })
    },
    deleteFile(prop, index, options) {
      this.$refs[prop][0].clearFiles()
      options['uploadFileName'] = ''
      this.formItems[index] = options
      // api 删除
    },
    disableFlag(value, prop) {
        this.form && this.form.disableFlag && this.form.disableFlag(value, prop)
    }
  }
}
</script>
